<?php
/**
 * Created by Administrator
 * User: longli
 * VX: isa1589518286
 * Date: 2020/08/12
 * Time: 10:49
 * @link http://www.lmterp.cn
 */

namespace app\common\service\platform;


use app\common\library\Tools;
use app\common\model\AccountSyncLog;
use app\common\model\OrdersTemp;
use app\common\service\orders\OrderService;
use think\facade\Log;

/**
 * Coupang 接口服务, 国内服务器无法访问，需要代理服务器
 * Class CoupangService
 * @package app\common\service\coupang
 * @link https://developers.coupang.com/hc/en-us/articles/360033877853-Product-Creation
 */
class CoupangService extends BasePlatformService
{
    public static $tokenField = [
        'required' => [ // 必填字段
            [
                'type' => 'text',
                'name' => 'vendor_id',
                'field' => 'vendor_id',
            ],
            [
                'type' => 'text',
                'name' => 'access_key',
                'field' => 'access_key',
            ],
            [
                'type' => 'text',
                'name' => 'secret_key',
                'field' => 'secret_key',
            ],
        ],
        'option' => [ // 可选字段
        ],
    ];

    /**
     * 获取订单列表
     * @param array $params 参数配置，默认抓取当天订单
     * <ul>
     * <li>string start_date 要抓取的时间，默认为今天</li>
     * <li>string end_date 要抓取的时间，默认为今天</li>
     * </ul>
     * @param bool $replace 是否替换原有的订单，默认不替换
     * @return array|bool
     * @date 2020/08/13
     * @author longli
     * @link https://developers.coupang.com/hc/en-us/articles/360033792774-PO-list-query-by-Minute-
     */
    public function getOrderList($params = [], $replace = false)
    {
        Log::info(sprintf("Coupang 批量同步账号【%d】订单，请求参数:【%s】", $this->getAccountId(), json_encode($params)));
        $account = $this->getAccount();
        $path = "/v2/providers/openapi/apis/api/v4/vendors/{$account->token->vendor_id}/ordersheets";
        $args = [
            "createdAtFrom" => !empty($params['start_date']) ? $params['start_date'] : date('Y-m-d', strtotime("-1day")), // 开始创建订单时间
            "createdAtTo" => !empty($params['end_date']) ? $params['end_date'] : date('Y-m-d'),
            "status" => !empty($params['status']) ? $params['status'] : "ACCEPT"
        ];
        $startSyncTime = time();
        $nextToken = null;
        do
        {
            if(!empty($nextToken)) $args['nextToken'] = $nextToken; // 设置下一页请求 token
            $sign = $this->getSignature($path, http_build_query($args));
            $header = ["Content-Type:application/json;charset=UTF-8", "Authorization:{$sign['auth']}"];
            $response = Tools::curlGet($sign['url'], [], $header);
            if(!$response['status'])
            {
                Log::info(sprintf("Coupang 订单接口请求发生错误:【%s】", json_encode($response['info'])));
                break;
            }
            if(!Tools::isJson($response['data'], $jsonData) && $jsonData['code'] != 200)
            {
                Log::info(sprintf("Coupang 订单接口返回错误:【%s】", json_encode($jsonData)));
                break;
            }
            foreach($jsonData['data'] as $item)
            {
                $this->pushOrderToTemp($item['orderId'], $item, $replace);
            }
            if(!empty($jsonData['nextToken'])) $nextToken = $jsonData['nextToken']; // 下一页令牌不为空
        }while(!empty($nextToken));
        // 添加同步订单日志
        AccountSyncLog::addLog($this->getAccountId(), $startSyncTime, time(), $args);
    }

    /**
     * 生成密钥
     * @param string $path 请求路径
     * @param string $queryStr 请求参数
     * @param string $method 请求方式，默认 get 请求
     * @date 2020/08/13
     * @return string[]
     *@author longli
     * @link https://api-gateway.coupang.com
     */
    public function getSignature($path, $queryStr = '', $method = 'GET')
    {
        Log::info(sprintf("账号[%d]计算签名", $this->getAccountId()));
        $method = strtoupper($method);
        $account = $this->getAccount();
        date_default_timezone_set("GMT+0");
        $datetime = date("ymd").'T'.date("His").'Z';
        date_default_timezone_set("Asia/Shanghai");
        $message = $datetime . $method . $path . $queryStr;
        $signature = hash_hmac('sha256', $message, $account->token->secret_key);
        $authorization  = "CEA algorithm=HmacSHA256, access-key={$account->token->access_key}, signed-date={$datetime}, signature={$signature}";
        $url = $this->getBaseUrl() . "$path?$queryStr";
        return ['url' => $url, 'auth' => $authorization];
    }

    public function syncOrder(OrdersTemp $ordersTemp)
    {
        $data = $ordersTemp->order_info;
        $info = [];
        $totalPrice = 0;
        foreach($data['orderItems'] as $item)
        {
            $totalPrice += $item['shippingCount'] * $item['salesPrice'];
            $info[] = [
                "item_id"       => $item['sellerProductId'], // 商品 id
                "qty"           => $item['shippingCount'], // 数量
                "return_qty"    => $item['cancelCount'], // 取消数量
                "price"         => $item['salesPrice'], // 单价
                "platform_sku"  => $item['externalVendorSkuCode'], // sku
                "name"          => $item['sellerProductName'], // 产品名称
                "url"           => "https://www.coupang.com/vp/products/{$item['vendorItemId']}", // 产品在平台链接
            ];
        }
        $platform = $this->getAccountById($ordersTemp->account_id)->platform;
        list($city, $district) = explode(' ', $data['receiver']['addr1']);
        $order = [
            "order_no"                  => $ordersTemp->order_no,
            "account_id"                => $ordersTemp->account_id,
            "platform_name"             => $platform->name, // 平台名称
            "order_platform_status"     => $data['status'], // 订单在平台的状态
            "buyer_first_name"          => $data['receiver']['name'], // 客户名称
            "buyer_email"               => $data['orderer']['email'], // 邮箱
            "buyer_phone"               => $data['receiver']['safeNumber'], // 电话
            "buyer_country_code"        => "KOR", // 国家编码
            "buyer_city"                => $city, // 城市
            "buyer_district"            => $district, // 区
            "buyer_post_code"           => $data['receiver']['postCode'], // 邮编
            "buyer_address_1"           => $data['receiver']['addr1'], // 买家收货地址1
            "buyer_address_2"           => $data['receiver']['addr2'], // 买家收货地址2
            "shipping_price"            => '0.00', // 订单运费
            "order_source_create_time"  => $this->parseTimeToDate($data['orderedAt']), // 订单在平台生成的时间
            "latest_delivery_time"      => $this->parseTimeToDate($data['orderItems'][0]['estimatedShippingDate']), // 最迟发货时间
            "order_price"               => $totalPrice, // 订单金额
            "total_price"               => $totalPrice, // 订单总金额
            "order_pay_time"            => $this->parseTimeToDate($data['orderItems'][0]['confirmDate']), // 订单支付时间
            "currency"                  => 'KRW', // 币种
            "platform_remark"           => $data['parcelPrintMessage'], // 买家备注信息
            "order_detail" => $info,
        ];
        return OrderService::getInstance()->addOrder($order);
    }

    public function markDelivery($orderIds = [])
    {
        // @todo 标记发货
    }
}